//
//  WDFBManager.m
//  WDPolymerizeSDK
//
//  Created by little People on 2023/6/12.
//

#import "WDFBManager.h"
#import "WDNSLog.h"
#import "WDCallBack.h"
#import "SUCache.h"
#import "WDCallBack.h"
#import "WDDefaultSysFunctionManager.h"
@import FBSDKLoginKit;
@import FBSDKShareKit;

@interface WDFBManager ()<FBSDKSharingDelegate>

@end

@implementation WDFBManager
static WDFBManager *_FBManager = nil;
+ (instancetype)shareFBManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _FBManager = [[self alloc] init];
        
    });
    return _FBManager;
}

- (void)FBApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[FBSDKApplicationDelegate sharedInstance] application:application
                               didFinishLaunchingWithOptions:launchOptions];
}

- (void)FBApplication:(UIApplication *)application
            openURL:(NSURL *)url
            options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    [[FBSDKApplicationDelegate sharedInstance] application:application
                                                     openURL:url
                                                     options:options];
}

- (void)FBLogin
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_updateContent:)
                                                 name:FBSDKProfileDidChangeNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_accessTokenChanged:)
                                                 name:FBSDKAccessTokenDidChangeNotification
                                               object:nil];
    SUCacheItem *item = [SUCache itemForSlot:0];
     [self labelDisplayWithProfile:item.profile];
    
    
    NSInteger slot = 0;
    FBSDKAccessToken *token = [SUCache itemForSlot:slot].token;
    if (token) {
        [self autoLoginWithToken:token];
    }
    else {
        [self newLogin];
    }
    
}

- (void)FBShareWithTitle:(NSString *)title url:(NSString *)url content:(NSString *)shareContent
{
    
    if (@available(iOS 13.0, *))
    {
        NSString * s = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc]init];
        content.contentURL = [NSURL URLWithString:s];
        
        content.hashtag = [[FBSDKHashtag alloc] initWithString:title];
        content.quote = shareContent;
        [FBSDKShareDialog showFromViewController:[UIApplication sharedApplication].keyWindow.rootViewController withContent:content delegate:self];
    }
    else
    {
        [[WDDefaultSysFunctionManager shareSysFunctionManager] sysShareFunctionWithTitle:title url:url];
    }
    
    
    
}

- (void)autoLoginWithToken:(FBSDKAccessToken *)token {
    WDLog(@"facebook login autoLoginWithToken");
    [FBSDKAccessToken setCurrentAccessToken:token];
    FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields":@""}];
    [request startWithCompletion:^(id<FBSDKGraphRequestConnecting>  _Nullable connection, id  _Nullable result, NSError * _Nullable error) {
        //token过期，删除存储的token和profile
        if (error) {
            WDLog(@"The user token is no longer valid.");
            if ([WDCallBack shareCallBack].onFbError)
            {
                [WDCallBack shareCallBack].onFbError(error.localizedDescription);
            }
            NSInteger slot = 0;
            [SUCache deleteItemInSlot:slot];
            [FBSDKAccessToken setCurrentAccessToken:nil];
            [FBSDKProfile setCurrentProfile:nil];
        }
        //做登录完成的操作
        else {
//            FBSDKLoginManagerLoginResult *newR = (FBSDKLoginManagerLoginResult *)result;
            WDLog(@"=====:%@",result);
            NSString *fid = [NSString stringWithFormat:@"%@",result[@"id"]];
            if ([WDCallBack shareCallBack].onFbSuccess)
            {
                [WDCallBack shareCallBack].onFbSuccess(fid);
            }
            [self getUserInfoWithResult:fid];
//            [self FBLoginCompleWithResult:result error:error];
        }
    }];
    
}

- (void)newLogin {
    WDLog(@"facebook login newLogin");
    UIViewController *rootController = [[[UIApplication sharedApplication].windows objectAtIndex:0] rootViewController];
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
//    [login logOut];
    [login logInWithPermissions:@[@"public_profile"] fromViewController:rootController handler:^(FBSDKLoginManagerLoginResult *_Nullable result, NSError *_Nullable error) {
        [self FBLoginCompleWithResult:result error:error];
    }];
}

- (void)FBLogOut
{
    NSInteger slot = 0;
    [SUCache deleteItemInSlot:slot];
    [FBSDKAccessToken setCurrentAccessToken:nil];
    [FBSDKProfile setCurrentProfile:nil];
    
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login logOut];
}

- (void)FBLoginCompleWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error
{
    if (error) {
        WDLog(@"Process error");
        if ([WDCallBack shareCallBack].onFbError)
        {
            [WDCallBack shareCallBack].onFbError(error.localizedDescription);
        }
        
    } else if (result.isCancelled) {
        if ([WDCallBack shareCallBack].onFbCancel)
        {
            [WDCallBack shareCallBack].onFbCancel();
        }
        WDLog(@"Cancelled: %@", error);
    } else {
        NSString *fid = result.token.userID;
        if ([WDCallBack shareCallBack].onFbSuccess)
        {
            [WDCallBack shareCallBack].onFbSuccess(fid);
        }
        [self getUserInfoWithResult:fid];
        WDLog(@"Logged in:%@",fid);
    }
}

//获取用户信息 picture用户头像
- (void)getUserInfoWithResult:(NSString *)userID
{
    NSDictionary*params= @{@"fields":@"id,name,email,age_range,first_name,last_name,link,gender,locale,picture,timezone,updated_time,verified"};
    
    FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                                  initWithGraphPath:userID
                                  parameters:params
                                  HTTPMethod:@"GET"];
    [request startWithCompletion:^(id<FBSDKGraphRequestConnecting>  _Nullable connection, id  _Nullable result, NSError * _Nullable error) {
        WDLog(@"%@",result);
        NSDictionary *picture = result[@"picture"];
        NSDictionary *data = picture[@"data"];
        NSString *imageUrl = data[@"url"];
        if (imageUrl.length > 0)
        {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:imageUrl]];
                UIImage *image = [UIImage imageWithData:data];
                if ([WDCallBack shareCallBack].onFbHeadImage)
                {
                    dispatch_async ( dispatch_get_main_queue (), ^{
                        [WDCallBack shareCallBack].onFbHeadImage(image);
                    });
                    
                }
            });
        }
        // 下边的部分 是我获取到的信息，剩下的信息可能是因为没有申请到权限吧
        // 现阶段用的开发者账号还是自己的，更多的可能性讲需要注册下来公司的账户，并开通相应的权限
        
//        {
//            "first_name" = Qingfeng;
//            id = 429690791177412;
//            "last_name" = Li;
//            name = "Qingfeng Li";
//            picture =     {
//                data =         {
//                    height = 50;
//                    "is_silhouette" = 0;
//                    url = "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=429690791177412&height=50&width=50&ext=1560396740&hash=AeQrpS9VqOZQ9-cK";
//                    width = 50;
//                };
//            };
//        }
    }];
    
    
}

#pragma mark - Notification

- (void)_updateContent:(NSNotification *)notification {
    FBSDKProfile *profile = notification.userInfo[FBSDKProfileChangeNewKey];
    [self labelDisplayWithProfile:profile];
}

- (void)_accessTokenChanged:(NSNotification *)notification
{
    FBSDKAccessToken *token = notification.userInfo[FBSDKAccessTokenChangeNewKey];
    if (!token) {
        [FBSDKAccessToken setCurrentAccessToken:nil];
        [FBSDKProfile setCurrentProfile:nil];
    } else {
        NSInteger slot = 0;
        SUCacheItem *item = [SUCache itemForSlot:slot] ?: [[SUCacheItem alloc] init];
        if (![item.token isEqualToAccessToken:token]) {
            item.token = token;
            [SUCache saveItem:item slot:slot];
        }
    }
}

- (void)labelDisplayWithProfile:(FBSDKProfile *)profile{
    NSInteger slot = 0;
    if (profile) {
        SUCacheItem *cacheItem = [SUCache itemForSlot:slot];
        cacheItem.profile = profile;
        [SUCache saveItem:cacheItem slot:slot];
//        self.infoLabel.text = [NSString stringWithFormat:@"name = %@,userID = %@",cacheItem.profile.name,cacheItem.profile.userID];
//       NSURL *imgURL = [profile imageURLForPictureMode:FBSDKProfilePictureModeNormal size:self.pictureView.frame.size];
//        [self.pictureView setImageByUrl:[NSString stringWithFormat:@"%@",imgURL]];
        
    }
}

#pragma mark - FBSDKSharingDelegate

- (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults:(NSDictionary *)results{

    WDLog(@"分享成功");
    if ([WDCallBack shareCallBack].onShareCallBack)
    {
        [WDCallBack shareCallBack].onShareCallBack(YES);
    }
}

- (void)sharer:(id<FBSDKSharing>)sharer didFailWithError:(NSError *)error{
    WDLog(@"分享失败");
    if ([WDCallBack shareCallBack].onShareCallBack)
    {
        [WDCallBack shareCallBack].onShareCallBack(NO);
    }
}

- (void)sharerDidCancel:(id<FBSDKSharing>)sharer{
    WDLog(@"分享取消");
    if ([WDCallBack shareCallBack].onShareCallBack)
    {
        [WDCallBack shareCallBack].onShareCallBack(NO);
    }
}



@end
